#!/bin/sh /etc/rc.common
# Copyright (C) 2007-2011 OpenWrt.org

START=50

append_bool() {
	local section="$1"
	local option="$2"
	local value="$3"
	local _val
	config_get_bool _val "$section" "$option" '0'
	[ "$_val" -gt 0 ] && append args "$3"
}

append_string() {
	local section="$1"
	local option="$2"
	local value="$3"
	local _val
	config_get _val "$section" "$option"
	[ -n "$_val" ] && append args "$3 $_val"
}

start_instance() {
	local section="$1"

	config_get_bool enabled "$section" 'enabled' '0'
	[ $enabled -gt 0 ] || return 1

	config_get pid_file "$section" 'pid_file'

	args=""
	append_string "$section" 'interface' '-i'
	append_string "$section" 'pcap_file' '-r'
	append_string "$section" 'timeout' '-t'
	append_string "$section" 'max_flows' '-m'
	append_string "$section" 'host_port' '-n'
	append_string "$section" 'pid_file' '-p'
	append_string "$section" 'control_socket' '-c'
	append_string "$section" 'export_version' '-v'
	append_string "$section" 'hoplimit' '-L'
	append_string "$section" 'tracking_level' '-T'
	append_string "$section" 'sampling_rate' '-s'
	append_bool "$section" track_ipv6 '-6'

	SERVICE_PID_FILE="$pid_file" \
	service_start /usr/sbin/softflowd $args${pid_file:+ -p $pid_file}
}

stop_instance() {
	local section="$1"

	config_get_bool enabled "$section" 'enabled' '0'
	[ $enabled -gt 0 ] || return 1

	config_get control_socket "$section" 'control_socket'

	[ -n "control_socket" -a -S $control_socket ] && {
		/usr/sbin/softflowctl -c $control_socket exit
	}
}

start() {
	mkdir -m 0755 -p /var/empty

	config_load 'softflowd'
	config_foreach start_instance 'softflowd'
}

stop() {
	config_load 'softflowd'
	config_foreach stop_instance 'softflowd'
	service_stop /usr/sbin/softflowd
}
